package com.duojuhe.security.shiro.filter;



import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.jsonutils.JsonUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限验证
 */
public class ShiroPermissionFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        try{
            Subject subject = getSubject(servletRequest, servletResponse);
            if (subject==null){
                return false;
            }
            String[] rolesArray = (String[]) o;
            //没有权限访问
            if (rolesArray == null || rolesArray.length == 0) {
                return false;
            }
            for (String s : rolesArray) {
                //若当前用户是rolesArray中的任何一个，则有权限访问
                if (subject.isPermitted(s)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        JsonUtils.write(resp, ServiceResult.fail(ErrorCodes.NO_AUTHORIZATION_ERROR));
        return false;
    }
}
